package com.jzo2o.orders.manager.listener;

/**
 * @author 随缘而愈
 * @version 1.0
 * @description TODO
 * @date 18/4/2024 下午2:25
 */

import cn.hutool.core.collection.CollUtil;

import com.alibaba.fastjson.JSON;
import com.jzo2o.api.trade.enums.TradingStateEnum;
import com.jzo2o.common.constants.MqConstants;
import com.jzo2o.common.model.msg.TradeStatusMsg;
import com.jzo2o.orders.manager.service.IOrdersCreateService;
import jakarta.json.Json;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;



@Slf4j
@Component
public class TradeStatusListener {
    @Resource
    private IOrdersCreateService ordersCreateService;

    /**
     * 更新支付结果
     * 支付成功
     *
     * @param msg 消息
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.Queues.ORDERS_TRADE_UPDATE_STATUS),
            exchange = @Exchange(name = MqConstants.Exchanges.TRADE, type = ExchangeTypes.TOPIC),
            key = MqConstants.RoutingKeys.TRADE_UPDATE_STATUS
    ))
    public void listenTradeUpdatePayStatusMsg(String msg) {
        // 解析消息
        List<TradeStatusMsg> tradeStatusMsgS = JSON.parseArray(msg, TradeStatusMsg.class);
        // 过滤消息
        tradeStatusMsgS.stream().filter(item-> "jzo2o.orders".equals(item.getProductAppId()) &&
                item.getStatusCode() == 4).collect(Collectors.toList());

        if (CollUtil.isEmpty(tradeStatusMsgS)) {
            return;
        }

        //修改订单状态
        tradeStatusMsgS.forEach(m -> ordersCreateService.paySuccess(m));
    }
}
